package com.jy.wms.service;

import PTLwebService.*;
import com.jy.wms.common.PropertyUtil;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.HttpUtil;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import net.sf.json.JSONObject;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.aspectj.weaver.ast.Call;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

    /**
    * @ClassName: WmsInventoryPlanService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Jane
    * @Date Tue Jan 09 10:16:55 CST 2018
    */

    @Service
    public class WmsInventoryPlanService extends BaseService<WmsInventoryPlanMapper,WmsInventoryPlan> {
        @Autowired
        private WmsInventoryTaskMapper wmsInventoryTaskMapper;//盘点任务Mapper
        @Autowired
        private WmsStockMapper stockMapper;//库存Mapper
        @Autowired
        private WmsInventoryMergeMapper wmsInventoryMergeMapper;//盘点任务合并Mapper
        @Autowired
        private WmsPdaMsgMapper wmsPdaMsgMapper;//pdamessager

        /**
         * 新增盘点计划
         *
         * @param entity 实体对象
         * @return int
         */
        @BaseServiceDescribe(moduleName = "新增盘点计划", btnName = "新增盘点计划信息")
        public void baseInsert(WmsInventoryPlan entity) throws ServiceException {
            Integer count = dao.countPdbhByPdbh(entity.getPdbh());//此编号是否已存在
            if (count > 0) {
                throw new ServiceException("此盘点编号已存在，请重新生成编号");
            }
            //用于时间转换
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //全仓盘点
            if ("1".equals(entity.getQcpd())) {
                if ((entity.getCpid() != null && !("".equals(entity.getCpid()))) && (entity.getKwid() != null && !("".equals(entity.getKwid()))) && (entity.getKqid() != null && !("".equals(entity.getKqid())))) {
                    throw new ServiceException("全仓盘点不需要指定库位库区或货品");
                }
                if ("1".equals(entity.getDppdzt()) && "1".equals(entity.getSjpd())) {
                    throw new ServiceException("全仓盘点，动态盘点，随机盘点只能选择一个！");
                }
                entity.setDpjssj("");
                entity.setDpkssj("");
                entity.setDppdzt("0");
                entity.setSjpd("0");
                entity.setKcs(new BigDecimal(0));
            }
            //动碰盘点
            if ("1".equals(entity.getDppdzt())) {
                if ("1".equals(entity.getSjpd())) {
                    throw new ServiceException("全仓盘点，动态盘点，随机盘点只能选择一个！");
                }
                if ((entity.getDpkssj() == null && "".equals(entity.getDpkssj())) || (entity.getDpjssj() == null && "".equals(entity.getDpjssj()))) {
                    throw new ServiceException("动态盘点必须选择一个时间段");
                } else if (Long.valueOf(entity.getDpkssj()) >= Long.valueOf(entity.getDpjssj())) {
                    //判断开始时间小于结束时间
                    throw new ServiceException("动态盘点开始时间要小于结束时间");
                }
                Date kssj = new Date(Long.valueOf(entity.getDpkssj()));
                Date jssj = new Date(Long.valueOf(entity.getDpjssj()));
                entity.setQcpd("0");
                entity.setSjpd("0");
                entity.setDpkssj(format.format(kssj));
                entity.setDpjssj(format.format(jssj));
                entity.setKcs(new BigDecimal(0));
            }
            //随机盘点
            if ("1".equals(entity.getSjpd())) {
                if (entity.getKcs().intValue() <= 0) {
                    throw new ServiceException("请为随机盘点填写一个库存数");
                }
                entity.setDpkssj("");
                entity.setDpjssj("");
                entity.setQcpd("0");
                entity.setDppdzt("0");
            }
            if (!(("1").equals(entity.getDtpd()))) {
                entity.setDtpd("0");
            }
            if (!("1".equals(entity.getKkw()))) {
                entity.setKkw("0");
            }
            if (!("1".equals(entity.getBhgdkw()))) {
                entity.setBhgdkw("0");
            }
            if (!("1".equals(entity.getMp()))) {
                entity.setMp("0");
            }
            Date date = new Date(Long.valueOf(entity.getSqsj()));
            entity.setSqsj(format.format(date));
            entity.setZt("0");//默认初始状态
            entity.setRwzt("0");//任务状态
            entity.setCyzt("0");//初始
            entity.setTzzt("1");//未调整
            Integer success = dao.baseInsertSelective(entity);
            if (success <= 0) {
                throw new ServiceException("新增盘点计划失败");
            }
        }

        /**
         * 盘点计划预检_Jane
         *
         * @param id 盘点计划Id
         * @return void
         */
        @BaseServiceDescribe(moduleName = "盘点计划预检", btnName = "盘点计划预检")
        public void planWaring(String id) throws SucessException {
            WmsInventoryPlan plan = dao.baseSelectByPrimaryKey(id);
            List<WmsStock> count = dao.countCzSl(plan);
            if (count.size() > 0) {
                throw new SucessException("此盘点计划有待操作数量，可能对盘点数量有影响");
            } else {
                throw new SucessException("此盘点计划暂无待操作数量");
            }
        }

        /**
         * 关闭盘点计划_Jane
         * @param id 盘点计划Id
         * @return void
         */
        @BaseServiceDescribe(moduleName = "关闭盘点计划", btnName = "关闭盘点计划")
        public void closePlan(String id) throws ServiceException {
            WmsInventoryPlan plan = dao.baseSelectByPrimaryKey(id);
            if ("0".equals(plan.getRwzt())) {
                plan.setZt("1");
                Integer count = dao.baseUpdateByPrimaryKeySelective(plan);
                if (count <= 0) {
                    throw new ServiceException("盘点计划关闭失败！");
                }
            } else {
                throw new ServiceException("此盘点计划已生成任务不能关闭！");
            }
        }

        /**
         * 关闭盘点计划_Jane
         *
         * @param id 盘点计划Id
         * @return void
         */
        @BaseServiceDescribe(moduleName = "生成盘点计划任务", btnName = "生成盘点计划任务")
        @Transactional
        public void addPlanRw(String id,String ckid,String sshzid) throws ServiceException {
            WmsInventoryPlan plan = dao.baseSelectByPrimaryKey(id);
            if ("0".equals(plan.getRwzt()) && "0".equals(plan.getZt())) {
                List<WmsStock> stocks = dao.seachPlanKc(plan,ckid,sshzid);//获取满足条件的库存
                if (stocks.size() > 0) {
                    WmsInventoryTask task = null;
                    for (WmsStock stock : stocks) {
                        task = new WmsInventoryTask();
                        task.setId(UUIDUtils.uuid());
                        task.setCyzt("0");//初始
                        task.setKcid(stock.getId());//库存Id
                        task.setJhsl(new BigDecimal(stock.getSl()));//计划数量
                        task.setPdsl(new BigDecimal(0));//盘点数量
                        task.setPlanId(id);
                        task.setTzzt("1");
                        task.setZyryId("");
                        WmsInventoryTask tasks=dao.seachGysmc(stock.getId());
                        task.setGys(tasks.getGys());
                        task.setHpmc(tasks.getHpmc());
                        task.setHpbh(tasks.getHpbh());
                        task.setPc(tasks.getPc());
                        task.setKwmc(tasks.getKwmc());
                        task.setScrq(tasks.getScrq().substring(0,tasks.getScrq().length()-2));
                        task.setTpm(tasks.getTpm());
                        wmsInventoryTaskMapper.baseInsert(task);
                    }
                // 生成盘点任务合并信息
                    List<WmsInventoryTask> tasks=wmsInventoryTaskMapper.seachXxByPdId(id);
                    WmsInventoryMerge merge=null;
                    for(WmsInventoryTask inventoryTask:tasks){
                        merge=new WmsInventoryMerge();
                        merge.setId(UUIDUtils.uuid());
                        merge.setCkid(plan.getCkid());
                        merge.setHpid(inventoryTask.getHpid());
                        merge.setHpbh(inventoryTask.getGoodsBh());
                        merge.setHpmc(inventoryTask.getGoodsMc());
                        merge.setKwmc(inventoryTask.getKwmc());
                        merge.setKwid(inventoryTask.getKwid());
                        merge.setPid(id);
                        merge.setJhsl(inventoryTask.getJhsl().intValue());
                        merge.setPdsl(0);
                        merge.setCyzt("0");
                        merge.setZyryId("");
                        WmsInventoryMerge merge1=dao.seachZdwmc(inventoryTask.getHpid());
                        merge.setHsl(merge1.getHsl());
                        merge.setZdwmc(merge1.getZdwmc());
                        merge.setXdwmc(merge1.getXdwmc());
                        wmsInventoryMergeMapper.insert(merge);
                        //修改盘点任务的合并信息
                       List<WmsInventoryTask> inventoryTasks= wmsInventoryTaskMapper.seachByKwAndHpAndPlanId(id,inventoryTask.getGoodsBh(),inventoryTask.getKwmc());//获取Id
                        for(WmsInventoryTask task1:inventoryTasks){
                            task1.setPdhbid(merge.getId());
                            wmsInventoryTaskMapper.updateHbidById(task1);
                        }
                    }
                } else {
                    throw new ServiceException("此盘点计划无满足条件的库存，请重新确定您要盘点的库存！");
                }
                plan.setRwzt("1");
                dao.baseUpdateByPrimaryKeySelective(plan);
            } else {
                throw new ServiceException("此盘点计划不能生成盘点任务！");
            }

        }

        /**
         * 取消盘点任务_Jane
         *
         * @param id 盘点计划Id
         * @return void
         */
        @BaseServiceDescribe(moduleName = "取消盘点任务", btnName = "取消盘点任务")
        public void closePlanRw(String id) throws ServiceException {
            WmsInventoryPlan plan = dao.baseSelectByPrimaryKey(id);//查询盘点计划信息
            if ("0".equals(plan.getZt()) && "1".equals(plan.getRwzt()) && "0".equals(plan.getFpzt())) {
                Integer d = wmsInventoryTaskMapper.baseDeleteByPrimaryKey(id);//删除盘点任务
                if (d > 0) {
                   Integer me= wmsInventoryMergeMapper.baseDeleteByPrimaryKey(id);
                   if(me>0) {
                       plan.setRwzt("0");
                       plan.setCyzt("0");
                       dao.baseUpdateByPrimaryKeySelective(plan);//修改任务状态
                   }else{
                       throw new ServiceException("此盘点任务合并取消失败！");
                   }
                } else {
                    throw new ServiceException("此盘点任务无对应的盘点库存！");
                }
            } else {
                throw new ServiceException("此盘点计划不能取消盘点计划！");
            }
        }

        /**
         * 查看库存盘点信息_Jane
         * @param entity 盘点计划Id
         * @return void
         */
        @BaseServiceDescribe(moduleName = "", btnName = "查看库存盘点信息")
            public List<WmsInventoryTask> getStockPlan(WmsInventoryTask entity) throws ServiceException {
                return  wmsInventoryTaskMapper.seachKcPd(entity);
        }

        /**查看库存盘点信息
         * 库存盘点_Jane
         *
         * @param list 库存盘点
         * @return void
         */
        @BaseServiceDescribe(moduleName = "库存盘点", btnName = "库存盘点")
        @Transactional
        public void addStockPlan(List<WmsInventoryTask> list) throws ServiceException {
            List<WmsInventoryTask> tasks=new ArrayList<>();
            for (WmsInventoryTask task : list) {
                //判断任务差异状态
                if (task.getJhsl().equals(task.getPdsl())) {
                    task.setCyzt("1");
                    task.setTzzt("0");
                } else {
                    task.setCyzt("2");
                    task.setTzzt("1");

                }
                wmsInventoryTaskMapper.baseUpdateByPrimaryKey(task);
              //  tasks.add(task);
            }
           // Integer count=wmsInventoryTaskMapper.baseUpdateByPrimaryKeySelective(tasks);
//            if (count <= 0) {
//                throw new ServiceException("库存盘点失败");
//            }
            //修改盘点任务合并的信息
            WmsInventoryTask task=wmsInventoryTaskMapper.seachSameByPdhbid(list.get(0).getPdhbid());
            WmsInventoryMerge merge=new WmsInventoryMerge();
            merge.setId(list.get(0).getPdhbid());
            merge.setPdsl(task.getPdsl().intValue());
            if(task.getJhsl().intValue()==task.getPdsl().intValue()){//设置差异状态
                merge.setCyzt("1");
            }else{
                merge.setCyzt("2");
            }
            wmsInventoryMergeMapper.baseUpdateByPrimaryKeySelective(merge);//更新
            //修改盘点计划差异状态
            WmsInventoryPlan plan = new WmsInventoryPlan();
            Integer plan1=wmsInventoryTaskMapper.seachCyzt(list.get(0).getPlanId());
            if (plan1>0) {
                plan.setCyzt("2");
                plan.setTzzt("1");
            } else {
                plan.setCyzt("1");
            }
            plan.setId(list.get(0).getPlanId());
            dao.baseUpdateByPrimaryKeySelective(plan);
        }

        /**
         * 查看库存调整单信息_Jane
         *
         * @param entity 盘点计划Id
         * @return void
         */
        @BaseServiceDescribe(moduleName = "生成库存调整单信息", btnName = "生成库存调整单信息")
        public Page<WmsInventoryTask> getStockCyRw(WmsInventoryTask entity) throws ServiceException {
            WmsInventoryPlan plan = dao.baseSelectByPrimaryKey(entity.getPlanId());//查询盘点计划明细
            //修改盘点计划状态为已确认
            Page<WmsInventoryTask> list=new Page<WmsInventoryTask>();
            PageHelper.startPage(entity.getPage(),entity.getRows());
            plan.setZt("2");
            Integer f = dao.baseUpdateByPrimaryKeySelective(plan);
            if (f > 0) {
                if ("2".equals(plan.getCyzt())) {
                    return (Page<WmsInventoryTask>) wmsInventoryTaskMapper.getStockCyRw(entity);//返回有差异未调整的数据
                } else {
                    throw new ServiceException("此盘点计划无差异或者已调整，请确认要调整的计划");
                }
            } else {
                throw new ServiceException("盘点计划状态修改失败");
            }
        }

        /**
         * 调整库存_Jane
         *
         * @param ids 盘点任务Ids
         * @return void
         */
        @BaseServiceDescribe(moduleName = "调整库存", btnName = "调整库存")
        @Transactional
        public void tzPlanRw(List<String> ids) throws ServiceException {
            List<WmsInventoryTask> tasks = wmsInventoryTaskMapper.baseSelectBathPrimaryKeys(ids);//获取要调整的库存信息
            for(WmsInventoryTask task:tasks){
                if("2".equals(task.getTzzt())){
                    throw new ServiceException("已选条数中已有调整过得库存请刷新页面重新选择！");
                }
            }
            Inventory inventory=new Inventory();//用于修改DPS库存
            if (tasks.size() > 0) {
                WmsStock stock = null;//用于修改库存
                //遍历调整
                for (WmsInventoryTask task : tasks) {
                    stock = new WmsStock();
                    inventory.setID(task.getKcid());
                    WmsInventoryTask task1=wmsInventoryTaskMapper.seachSameByPdhbid(task.getPdhbid());
                    inventory.setItemNum(task1.getPdsl().intValue());
                    inventory.setCLocation(task.getKwmc());
                    inventory.setProNO(task.getHpbh());
                    String dwmc=wmsInventoryTaskMapper.seachDwmc(task.getHpbh());
                    inventory.setUnitName(dwmc);
                    inventory.setFlag(2);
                    stock.setId(task.getKcid());
                    stock.setSl(task.getPdsl().toString());
                    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    stock.setYdsj(format.format(new Date()));
                    stockMapper.baseUpdateByPrimaryKeySelective(stock);//调整库存
                    task.setTzzt("2");
                    wmsInventoryTaskMapper.baseUpdateByPrimaryKey(task);
                    if("dps".equals(task.getZyryId())) {
                        logger.info(inventory.toString());
                        Service1 service1 = new Service1();
                        Service1Soap service1Soap = service1.getService1Soap();
                        Result result = service1Soap.modifyInventory(inventory);
                        if ("S".equals(result.getResult())) {

                        } else {
                            throw new RuntimeException(result.getSMsg());
                        }
                    }
                }
                    WmsInventoryPlan plan = dao.baseSelectByPrimaryKey(tasks.get(0).getPlanId());//查询盘点计划明细
                    if ("1".equals(plan.getTzzt())) {
                        plan.setTzzt("2");
                        dao.baseUpdateByPrimaryKeySelective(plan);
                    }
              //  }
            } else {
                throw new ServiceException("请选择正确的盘点任务明细");
            }
        }


        /**
         * 打印盘点任务清单_Jane
         *
         * @param entity 实体
         * @return Page<WmsInventoryPlan>
         */
        @BaseServiceDescribe(moduleName = "打印盘点任务清单", btnName = "打印盘点任务清单")
        public JSONObject printPlanRw(WmsInventoryTask entity,String ry) {
            JSONObject object=new JSONObject();
            object=printTT(entity,ry);
            PageHelper.startPage(entity.getPage(), entity.getRows());
            Page<WmsInventoryTask> task=(Page<WmsInventoryTask>) dao.printPlanRw(entity);
            object.put("list",task);
            return object;
        }

        /**
         * 打印盘点损益单_Jane
         *
         * @param entity 实体
         * @return Page<WmsInventoryPlan>
         */
        @BaseServiceDescribe(moduleName = "打印盘点损益单", btnName = "打印盘点损益单")
        public JSONObject printSYPlanRw(WmsInventoryTask entity,String ry) {
            JSONObject object=new JSONObject();
            object=printTT(entity,ry);
            PageHelper.startPage(entity.getPage(), entity.getRows());
            Page<WmsInventoryTask> task=(Page<WmsInventoryTask>) dao.printSYPlanRw(entity);
            object.put("list",task);
            return object;
        }
        /**
         * 打印表头_Jane
         *
         * @param entity 实体
         * @return Page<WmsInventoryPlan>
         */
        @BaseServiceDescribe(moduleName = "打印盘点表头", btnName = "打印盘点表头")
        public JSONObject printTT(WmsInventoryTask entity,String ry) {
            JSONObject object=new JSONObject();
            WmsInventoryPlan plans=dao.baseSelectByPrimaryKey(entity.getPlanId());
            object.put("盘点计划",plans.getPdbh());
            String pdlx="";
            if("1".equals(plans.getQcpd())){
                pdlx="全仓盘点";
            }else if("1".equals(plans.getDppdzt())){
                pdlx="动碰盘点";
            }else if("1".equals(plans.getSjpd())){
                pdlx="随机盘点";
            }
            object.put("盘点类型",pdlx);
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            object.put("打印时间",format.format(new Date()));
            object.put("打印人员",ry);
            object.put("盘点人员","");
            return object;
        }
        /**
         * 分页查询
         *
         * @param entity 实体
         * @return Page<WmsInventoryPlan>
         */
        @BaseServiceDescribe(moduleName = "查询盘点计划信息", btnName = "查询盘点计划信息")
        public Page<WmsInventoryPlan> baseSelectPage(WmsInventoryPlan entity) {
            PageHelper.startPage(entity.getPage(), entity.getRows());
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(entity.getSqsj_start()!=null && entity.getSqsj_start()!=""){
                Date date =new Date(new Long(entity.getSqsj_start()));
                entity.setSqsj_start(format.format(date));
            }
            Calendar c=Calendar.getInstance();
            if (entity.getSqsj_end() != null && entity.getSqsj_end() != "") {
                c.setTime(new Date(Long.valueOf(entity.getSqsj_end())));
                c.set(Calendar.HOUR_OF_DAY, 23);
                c.set(Calendar.MINUTE, 59);
                c.set(Calendar.SECOND, 59);
                entity.setSqsj_end(format.format(c.getTime()));
            }
            return (Page<WmsInventoryPlan>) dao.baseSelectPage(entity);
        }

        /**
         * 查询（根据主键ID查询）
         *
         * @param id 主键ID
         * @return WmsInventoryPlan
         */
        public WmsInventoryPlan baseSelectByPrimaryKey(String id) {
            return dao.baseSelectByPrimaryKey(id);
        }

        /**
         * 查询（根据ID 批量查询）
         *
         * @param idList 主键ID列表
         * @return list
         */
        public Integer baseSelectBathPrimaryKeys(List<WmsInventoryPlan> idList) {
            return dao.baseSelectBathPrimaryKeys(idList);
        }


        /**
         * 新建盘点编号
         *
         * @param ckid
         * @param owner
         * @return
         * @throws Exception
         */
        @BaseServiceDescribe(moduleName = "新建盘点编号", btnName = "新建盘点编号")
        public String creatPdBh(String ckid, String owner) throws Exception {
            try {
                String bh = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                Date time = new Timestamp(System.currentTimeMillis());
                String bcTime = sdf.format(time);
                int number = dao.selectBcNoCountInOneDay(bcTime, ckid, owner);//判断当天是否有盘点计划
                if (number != 0) {
                    String num = dao.selectBcNumInOneDay(bcTime, ckid, owner);//查询出当天盘点计划的最大值
                    String newNum = num.replaceAll("^(0+)", "");
                    int bhno = Integer.parseInt(newNum) + 1;
                    String str = String.format("%4d", bhno).replace(" ", "0");
                    bh = bcTime + str;
                } else {
                    bh = bcTime + "0001";
                }
                return bh;
            } catch (Exception e) {
                throw new ServiceException("新建盘点编号", e);
            }
        }

        /**
         * 下发盘点计划回传信息
         *
         * @param plan
         * @return
         * @throws Exception
         */
        @BaseServiceDescribe(moduleName = "下发盘点计划回传信息", btnName = "下发盘点计划回传信息")
        public void backlogPlan(BlacklogPlan plan) throws ServiceException {
            Assert.notNull(plan.getPlanId(), "The country's planId must not be null");
            Assert.notNull(plan.getPlanNO(), "The country's planNO must not be null");
            Assert.notNull(plan.getGoodsnumber(), "The country's goodsnumber must not be null");
            Assert.notNull(plan.getLocationName(), "The country's locationName must not be null");
            Assert.notNull(plan.getPlanNum(), "The country's planNum must not be null");
            Assert.notNull(plan.getIntemNum(), "The country's InventoryNum must not be null");
            Assert.notNull(plan.getFlag(), "The country's differenceState must not be null");
            //修改盘点合并数量
            WmsInventoryMerge merge=new WmsInventoryMerge();
            merge.setHpbh(plan.getGoodsnumber());
            merge.setKwmc(plan.getLocationName());
            merge.setPid(plan.getPlanId());
            WmsInventoryMerge mergeList=wmsInventoryMergeMapper.baseByHebingId(merge);
            if(mergeList!=null){
                merge.setId(mergeList.getId());
                merge.setPdsl(Integer.parseInt(plan.getIntemNum()));
                if("1".equals(plan.getFlag())){
                    merge.setCyzt("2");
                }else{
                    merge.setCyzt("1");
                }

                wmsInventoryMergeMapper.baseUpdateByPrimaryKeySelective(merge);
            }else{
                throw new ServiceException("此数据已移除请对照数据");
            }
            List<WmsInventoryTask> taskList = wmsInventoryTaskMapper.seachByKwAndHpAndPlanId(plan.getPlanId(), plan.getGoodsnumber(), plan.getLocationName());
            if ("0".equals(plan.getFlag()) && Integer.parseInt(plan.getPlanNum()) == Integer.parseInt(plan.getIntemNum())) {
                //无差异
                for (WmsInventoryTask task : taskList) {
                    task.setPdsl(task.getJhsl());
                    task.setCyzt("1");
                    wmsInventoryTaskMapper.baseUpdateByPrimaryKey(task);
                }
             //  wmsInventoryTaskMapper.baseUpdateByPrimaryKeySelective(taskList);

            } else if ("1".equals(plan.getFlag()) && Integer.parseInt(plan.getPlanNum()) != Integer.parseInt(plan.getIntemNum())) {
                //有差异
                for (WmsInventoryTask task : taskList) {
                    task.setPdsl(new BigDecimal(0));
                    task.setCyzt("2");
                    wmsInventoryTaskMapper.baseUpdateByPrimaryKey(task);
                }
              //  wmsInventoryTaskMapper.baseUpdateByPrimaryKeySelective(taskList);
            } else {
                new ServiceException("盘点计划差异状态异常");
            }
            Integer count = wmsInventoryTaskMapper.cyztByplanId(plan.getPlanId());
            if (count > 0) {
                WmsInventoryPlan plan1 = new WmsInventoryPlan();
                plan1.setId(plan.getPlanId());
                plan1.setCyzt("2");
                dao.baseUpdateByPrimaryKeySelective(plan1);
            }
        }

        /**
         * 下发盘点计划回传信息
         *
         * @param planId
         * @return
         * @throws Exception
         */
        @Transactional
        public JSONObject addCxfInventoryPlan(String planId,String sshzid,String zyryid,String zyrymc) throws ServiceException {
            JSONObject object=new JSONObject();
            //查看此计划是否已分配
            //查询此货主的pda和dps操作是否启用
            String result="";
            WmsOwner owner = dao.seachOwnerXxById(sshzid);
            if ("0".equals(owner.getDjdps()) && "0".equals(owner.getDjpda())) {
                throw new ServiceException("此货主没有绑定pda或者dps操作，请点击盘点电脑端操作");
            } else {
                WmsInventoryPlan plan1 = dao.baseSelectByPrimaryKey(planId);//查询盘点信息判断状态是否符合
                if("1".equals(plan1.getXfzt())) {
                    throw new ServiceException("此盘点已经下发过，不能重复下发");
                }
                if ("1".equals(plan1.getRwzt())) {
                    //修改分配状态
                    WmsInventoryPlan plan = new WmsInventoryPlan();
                    plan.setFpzt("1");
                    plan.setId(planId);
                    dao.baseUpdateByPrimaryKeySelective(plan);//更新分配状态
                    //推送dps

                    if ("1".equals(owner.getDjdps())) {
                       result=pdsDj(planId);//对接pds
                }
                    //推送pda
                    if ("1".equals(owner.getDjpda())) {
                        pdaDj(planId,plan1.getPdbh(),owner.getDjdps(),zyryid,zyrymc);
                    }
                }
                    WmsInventoryPlan plan=new WmsInventoryPlan();
                    plan.setId(planId);
                    plan.setXfzt("1");
                    dao.baseUpdateByPrimaryKeySelective(plan);

                object.put("result",result);
                return object;
            }
        }
        /**
         * pda对接
         * @param planId
         * @return
         * @throws Exception
         */
        public void pdaDj(String planId,String pdbh,String djdps, String zyryid,String zyrymc) throws ServiceException {
            List<WmsInventoryTask> taskList=new ArrayList<>();
            List<WmsInventoryMerge> mergerList=new ArrayList<>();
            WmsInventoryMerge merge=null;
            if("0".equals(djdps)){
                List<WmsInventoryTask> tasks=wmsInventoryTaskMapper.seachDPSJhwByPlanId(planId);
                if(tasks.size()>0){
                    WmsInventoryTask t=null;
                    for(WmsInventoryTask task:tasks){
                        t=new WmsInventoryTask();
                        t.setZyryId(zyryid);
                        t.setZyrymc(zyrymc);
                        t.setPdhbid(task.getPdhbid());
                        wmsInventoryTaskMapper.updateZyryid(t);
                        merge=new WmsInventoryMerge();
                        merge.setId(task.getPdhbid());
                        merge.setZyryId(zyryid);
                        wmsInventoryMergeMapper.udateZyryidDg(merge);
                        // mergerList.add(merge);
                    }
                }
            }
            List<WmsInventoryTask> inventoryTasks=wmsInventoryTaskMapper.seachPDAfpByPlanId(planId);
            WmsInventoryTask t=null;
            if(inventoryTasks.size()>0) {
                for (WmsInventoryTask task : inventoryTasks) {
                    t = new WmsInventoryTask();
                    t.setZyryId(zyryid);
                    t.setPdhbid(task.getPdhbid());
                    t.setZyrymc(zyrymc);
                    wmsInventoryTaskMapper.updateZyryid(t);
                    merge = new WmsInventoryMerge();
                    merge.setId(task.getPdhbid());
                    merge.setZyryId(zyryid);
                    wmsInventoryMergeMapper.udateZyryidDg(merge);
                    //  mergerList.add(merge);
                }
            }
           //     int c=wmsInventoryMergeMapper.updateZyryid(mergerList);

                  //  WmsInventoryPlan plan=dao.baseSelectByPrimaryKey(planId);
                    SimpleDateFormat sdf=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                   // logger.info(plan.toString());
                    //给PDA推送消息
                    WmsPdaMsg msg = new WmsPdaMsg();
                    msg.setRyid(zyryid);
                    msg.setBt(pdbh);
                    msg.setXx(sdf.format(new Date())+"下发盘点任务");
                    wmsPdaMsgMapper.baseInsertSelective(msg);

        }
        /**
         * pds对接
         * @param planId
         * @return
         * @throws Exception
         */

        public String pdsDj(String planId) throws ServiceException {
            CheckInventory plans = new CheckInventory();//用于返回结果
            List<WmsInventoryTask> tasks = wmsInventoryTaskMapper.seachDPSJhwByPlanId(planId);
            if (tasks.size() > 0) {
                if ("dps".equals(tasks.get(0).getZyryId())) {//分配过则不需要分配
                    return "此单据已经分配过，不可再次分配";
                }
                plans.setID(UUIDUtils.uuid());
                plans.setPlanId(tasks.get(0).getPlanId());
                plans.setPlanNo(tasks.get(0).getPdbh());
                List<Goods> goodss = new ArrayList<>();

                Goods goods = null;
               // List<WmsInventoryMerge> merges = new ArrayList<>();

                WmsInventoryMerge merge = null;
                for (WmsInventoryTask task : tasks) {
                    goods = new Goods();
                    goods.setLocationName(task.getKwmc());
                    goods.setGoodsnumber(task.getGoodsBh());
                    goods.setPlanNum(task.getJhsl().intValue());
                    goodss.add(goods);
                    task.setZyryId("dps");
                    task.setZyrymc("dps");
                    merge = new WmsInventoryMerge();
                    merge.setId(task.getPdhbid());
                    merge.setZyryId("dps");
                    wmsInventoryTaskMapper.updateZyryid(task);//更新操作人员
                    wmsInventoryMergeMapper.udateZyryidDg(merge);

                }
               // wmsInventoryMergeMapper.updateZyryid(merges);
                ArrayOfGoods arrayOfGoods = new ArrayOfGoods();
                arrayOfGoods.setGoods(goodss);
                plans.setGoods(arrayOfGoods);
               Service1 service1 = new Service1();
                Service1Soap service1Soap = service1.getService1Soap();
                Result result = service1Soap.sendCheckInventoryData(plans);
                if ("s".equals(result.getResult())) {
                    return result.getResult();
                } else {
                   return "pds下发失败";
              }
            } else {
                return "此盘点计划无拣货位盘点";
            }
        }

    }
